/*---------------------------------------------------------------------------*\
|* This file is part of the koala project with MIT License.                  *|
|* Copyright (c) James <zhuguangxiang@gmail.com>                             *|
\*--------------------------------------------------------------------------**/

#ifndef _KOALA_LOG_H_
#define _KOALA_LOG_H_

#include "useful.h"

#ifdef __cplusplus
extern "C" {
#endif

#define __FILE_NAME__                         \
    ({                                        \
        char *slash = strrchr(__FILE__, '/'); \
        slash != NULL ? slash + 1 : __FILE__; \
    })

#ifdef NOLOG

#define log_set_level(level) ((void)0)
#define log_debug(fmt, ...)  ((void)0)
#define log_info(fmt, ...)   ((void)0)
#define log_warn(fmt, ...)   ((void)0)
#define log_error(fmt, ...)  ((void)0)
#define print(fmt, ...)      ((void)0)
#define println(fmt, ...)    ((void)0)
#define expect(fmt, ...)     ((void)0)

#else /* !NOLOG */

void log_set_level(int level);
void log_log(int level, char *file, int line, char *fmt, ...);

enum { LOG_DEBUG, LOG_INFO, LOG_WARN, LOG_ERROR };

#define log_debug(fmt, ...) \
    log_log(LOG_DEBUG, __FILE_NAME__, __LINE__, fmt, ##__VA_ARGS__)
#define log_info(fmt, ...) \
    log_log(LOG_INFO, __FILE_NAME__, __LINE__, fmt, ##__VA_ARGS__)
#define log_warn(fmt, ...) \
    log_log(LOG_WARN, __FILE_NAME__, __LINE__, fmt, ##__VA_ARGS__)
#define log_error(fmt, ...) \
    log_log(LOG_ERROR, __FILE_NAME__, __LINE__, fmt, ##__VA_ARGS__)

#define print(fmt, ...)   fprintf(stdout, fmt, ##__VA_ARGS__)
#define println(fmt, ...) fprintf(stdout, fmt "\n", ##__VA_ARGS__)

#define expect(expr)                                                     \
    if (!(expr)) {                                                       \
        fprintf(stderr, "%s:%d: expect '%s'\n", __FILE_NAME__, __LINE__, \
                #expr);                                                  \
        abort();                                                         \
    }

#endif

#define PANIC_COLOR "\x1b[35m"

#define panic(fmt, ...)                                              \
    do {                                                             \
        fprintf(stderr, PANIC_COLOR "panic\x1b[0m %s:%d: " fmt "\n", \
                __FILE_NAME__, __LINE__, ##__VA_ARGS__);             \
        abort();                                                     \
    } while (0)

#ifdef __cplusplus
}
#endif

#endif /* _KOALA_LOG_H_ */
